<?php
/**
 * 抢购活动管理
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
class PUserController extends Controller
{
    protected $model;
    protected $return;
    protected $start = '2017-01-27 00:00:00';
    protected $end = '2017-02-02 23:59:59';

    public function __construct(){
        header("Access-Control-Allow-Origin: *");
        $this->model = D('PUser');
        $this->return = array('errcode'=>0, 'errmsg'=>'ok');
        if(ACTION_NAME != 'login'){
            $admin = session('rush_admin');
            if (!$admin) {
                $this->ajaxReturn(array('errcode'=>10000,'errmsg'=>'请先登录'));
            }
        }
    }

    public function index()
    {
        $data['phone'] = I('post.phone', '', 'trim');
        $data['account'] = I('post.account', '', 'trim');
        $data['name'] = I('post.name', '', 'trim');
        $data['page'] = I('post.page', 1, 'intval');
        $data['page_size'] = I('page_size', 10, 'intval');

        $res = $this->model->getUserList($data);

        if ($res) {
            return $this->ajaxReturn(array_merge($this->return, $res));
        }else{
            return $this->ajaxReturn($this->model->getErrMsg());
        }
    }

    public function export()
    {
        $data['phone'] = I('get.phone', '', 'trim');
        $data['account'] = I('get.account', '', 'trim');
        $data['name'] = I('get.name', '', 'trim');

        $res = $this->model->getUserList($data, true);

        header("Content-type:text/csv");   
        header("Content-Disposition:attachment;filename=用户名单.csv");   
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');   
        header('Expires:0');   
        header('Pragma:public');  
        echo iconv("UTF-8", "GB2312", "姓名").",";
        echo iconv("UTF-8", "GB2312", "手机号码").",";
        echo iconv("UTF-8", "GB2312", "银行卡").",";
        echo iconv("UTF-8", "GB2312", "积分").",";
        echo iconv("UTF-8", "GB2312", "金额").",";
        echo iconv("UTF-8", "GB2312", "完成任务ID").",";
        echo iconv("UTF-8", "GB2312", "完成任务获得积分").",";
        echo iconv("UTF-8", "GB2312", "注册时间");
        echo iconv("UTF-8", "GB2312", "寄送地址");

        echo "\n";
        foreach ($res as $v) {
            echo iconv("utf-8", "gb2312//IGNORE", $v['name'])."\t,";
            echo $v['phone']."\t,";
            echo $v['account']."\t,";
            echo $v['score']."\t,";
            echo "\t,";
            echo "\t,";
            echo "\t,";
            echo date('Y-m-d H:i', $v['add_time'])."\t,";
            echo $v['address']."\t\n";

        }
        exit;

        // header("Content-type:application/vnd.ms-excel"); 
        // header("Content-Disposition:filename=用户名单.xls"); 

        // echo iconv("UTF-8", "GB2312", "姓名")."\t";
        // echo iconv("UTF-8", "GB2312", "手机号码")."\t";
        // echo iconv("UTF-8", "GB2312", "银行卡")."\t";
        // echo iconv("UTF-8", "GB2312", "积分")."\t\n";
        // foreach ($res as $v) {
        //     echo iconv("UTF-8", "GB2312", $v['name'])."\t";
        //     echo $v['phone']."\t";
        //     echo $v['account']."\t";
        //     echo $v['score']."\t\n";
        // }
        // $sheetindex=array(
        //     'A'=>array('index'=>'A1','name'=>'姓名','size'=>'20'),
        //     'B'=>array('index'=>'B1','name'=>'手机号码','size'=>'20'),
        //     'C'=>array('index'=>'C1','name'=>'银行卡','size'=>'20'),
        //     'E'=>array('index'=>'D1','name'=>'积分','size'=>'20'),
        // );
        // $title = '用户名单';
        // $type = 20;
        // ini_set("memory_limit", "1024M");
        // set_time_limit(0);
        // phpExcel($sheetindex,$res,$title,$type);
        // exit;
    
    }
    
    public function record()
    {
        $data['phone'] = I('post.phone', '', 'trim');
        $data['account'] = I('post.account', '', 'trim');
        $data['name'] = I('post.name', '', 'trim');
        $data['operate_type'] = I('post.operate_type', 0, 'intval'); 
        $data['type'] = I('post.type', 0, 'trim');
        $data['timeType']=I('post.timeType',0,'trim');
        Log::write(''.$data['type']);
        $data['start'] = I('post.start', '', 'trim');
        $data['end'] = I('post.end', '', 'trim');

        $data['pageIndex'] = I('post.page') ?: 1;
        $data['pageSize']  = I('post.page_size') ?: 20;
        $res = $this->model->getRecordList($data);

        if ($res) {
            return $this->ajaxReturn(array_merge($this->return, $res));
        }else{
            return $this->ajaxReturn($this->model->getErrMsg());
        }

    }

    public function recordExport()
    {
        ini_set("memory_limit", "218M");
        set_time_limit(0);
        $data['phone'] = I('get.phone', '', 'trim');
        $data['account'] = I('get.account', '', 'trim');
        $data['name'] = I('get.name', '', 'trim');
        $data['operate_type'] = I('get.operate_type', 0, 'intval');
        $data['type'] = I('get.type', 0, 'trim');
        $data['timeType']=I('get.timeType',0,'trim');
        Log::write(''.$data['type']);
        $data['start'] = I('get.start', '', 'trim');
        $data['end'] = I('get.end', '', 'trim');
        $data['pageIndex'] = 1;
        $data['pageSize']  = 1000; //每次查找1000条数据
        

        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=积分记录.csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        //打开输出流
        $fp = fopen('php://output', 'a');  
        //写入标题
        $title = array("姓名","手机号码","银行卡","积分","积分类型","操作时间","年限");
        foreach ($title as $key => $value) {
            $title[$key] = iconv("UTF-8", "GB2312", $value);
        }
        fputcsv($fp, $title);

        //获取总条数
        $total = D('PUser')->getCount($data);
        for($i = 0;$i<ceil($total/$data['pageSize']);$i++){
            $pRecord = D('PUser')->getRecordList($data, false, $total);
            $list=$pRecord['data'];
            foreach ($list as $key => $row) {
                $down['name'] = iconv("utf-8", "gb2312//IGNORE", $row['name']);
                $down['phone'] = $row['phone'];
                $down['account'] = $row['account'];
                $down['score'] = $row['score'];
                $down['type'] = iconv("utf-8", "gb2312//IGNORE", $row['type']);
                $down['add_time'] = $row['add_time'];
                $down['time_type'] = iconv("utf-8", "gb2312//IGNORE", $row['time_type']);
                fputcsv($fp, $down);
            }
            //清空缓存
            ob_flush();
            flush();
            //查找下一页数据
            $data['pageIndex']++;
        }
        exit();

        $str='';
        $str=iconv("UTF-8", "GB2312", "姓名").",";
        $str=$str.iconv("UTF-8", "GB2312", "手机号码").",";
        $str=$str.iconv("UTF-8", "GB2312", "银行卡").",";
        $str=$str.iconv("UTF-8", "GB2312", "积分").",";
        $str=$str.iconv("UTF-8", "GB2312", "积分类型").",";
        $str=$str.iconv("UTF-8", "GB2312", "操作时间").",";
        $str=$str.iconv("UTF-8", "GB2312", "年限");

        $str=$str."\n";
        foreach ($list as $v) {
            $str=$str.iconv("utf-8", "gb2312//IGNORE", $v['name'])."\t,";
            $str=$str.$v['phone']."\t,";
            $str=$str.$v['account']."\t,";

            $str=$str.$v['score']."\t,";
            $str=$str.iconv("utf-8", "gb2312//IGNORE", $v['type'])."\t,";
            $str=$str.$v['add_time']."\t,";
            $str=$str.iconv("utf-8", "gb2312//IGNORE", $v['time_type'])."\t\n";
        }

        echo $str;
        exit;


    }

    public function import()
    {

        if(!empty($_FILES)){

            $config = array(
                'exts'=>array('csv'),
                'maxSixe' => 1024 * 1024 * 5,
                'rootPath' =>'./Uploads/',
                'savePath' =>'image/',
                'subName'  =>array('date', 'Ymd'),
                'driver' =>'Local'
                );
            $upload = new \Think\Upload($config);
            if(!$info = $upload->upload()){
                $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>$upload->getError()));
            }
            $filename = $upload->rootPath.$info['file']['savepath'].$info['file']['savename'];

            $model = M("PUser");
            $model->startTrans();
            $update = true;

            $expire=M('PConfig')->where(array('key'=>'import_expire'))->find();


            $handle = fopen($filename, 'r');

            while($data = fgetcsv($handle)){

                if(count($data) < 6){
                    continue;
                }
                $name = iconv('gb2312', 'utf-8', $data[0]);
                $name = trim($name);
                $phone = trim($data[1]);
                $account = trim($data[2]);
                $amount = $data[4];
                $taskid=$data[5];
                $task_scope=0;
                if (empty($name)) {
                    continue;
                }
                if($name == '姓名' and $phone == '手机号码'){
                    continue;
                }

                if(!empty($taskid)){      //如果任务id不为空，则代表完成了任务

                    $map['account'] = $account;
                    $map['phone'] = $phone;


                    $user = $model->where($map)->find();
                    if($user){
                        $taskWhereParam['user_id']=$user['id'];


                        $tmpModel=M("PTaskPerson")->where($taskWhereParam)->find();

                        if($tmpModel && intval($tmpModel['finish_time'])<1){

                            //再添加任务的积分，
                            $task_scope=trim($data[6]);

                            $task_scope=intval($task_scope);
                            $taskWhereParam['user_id']=$user['id'];
                            $taskWhereParam['task_id']=$taskid;

                            //先完成任务
                            $tmpModel['finish_time']=time();
                            $tmpModel['scope']=$task_scope;
                            M("PTaskPerson")->where($taskWhereParam)->save($tmpModel);

                            unset($taskWhereParam);
                            $taskWhereParam['id']=$taskid;
                            $tmpModel=M("PTask")->where($taskWhereParam)->find();

                            if($tmpModel){
                                $tmpModel['finish_count']+=1;
                                M("PTask")->where($taskWhereParam)->save($tmpModel);
                            }
                        }

                    }


                }

                $amount = trim($amount);

                if (empty($amount)) {//金额为空，不处理
                    if($task_scope>0){
                        $record['user_id'] = $user['id'];
                        $record['score'] = $task_scope;
                        $record['consume'] = $task_scope;
                        $record['expire_time']=time()+$expire['value']*3600*24;

                        $record['add_time'] = time();
                        $record['type'] = 2;
                        $scoreRes = M("PScoreRecord")->add($record);
                        if(!$scoreRes){
                            $update = false;
                            break;
                        }
                    }
                    continue;
                }

                //$amount = str_replace(',', '', $amount);
                $amount = intval($amount);


                //3月31日~4月7日临时积分规则，每多1w积分加30，封顶积分60w
                $tmpStart = strtotime("2017-03-31 00:00:00");
                $tmpEnd = strtotime("2017-04-07 23:59:59");
                $now = time();
                if($now >= $tmpStart && $now <= $tmpEnd){
                    if($amount < 10000){
                        continue;
                    }
                    $amount= intval($amount / 10000);
                    $amount = intval($amount * 10000);
                    $times = intval($amount / 10000);
                    $score = intval(30 * $times);
                    if($score > 15000){
                        $score = 15000;
                    }
                }else{

                    if ($amount <= 0) { //负增长，不处理
                    continue;
                    }elseif ($amount < 10000){   //资金小于10000，不处理
                        continue;
                    }elseif ($amount < 50000){  //5W以下加50积分
                        $score = 58;
                    }elseif ($amount < 100000){
                        $score = 108;
                    }elseif ($amount < 500000){
                        $score = 158;
                    }else{
                        $score = 208;
                    }

                    /*
                    if ($amount <= 0) { //负增长，不处理
                    continue;
                    }elseif ($amount < 10000){   //资金小于10000，不处理
                        continue;
                    }else{
                        $score=intval($amount/10000)*30;
                        if($score>15000)
                            $score=15000;
                    }
                    */
                }
                
                //$start = strtotime($this->start);
                //$end = strtotime($this->end);
                //$now = time();
                //特定时期积分加倍

                //if ($now >= $start and $now <= $end) {
                //    $score = $score * 2;
                //}

                $map['phone'] = trim($phone);
                //$map['name'] = trim($name);
                $map['account'] = trim($account);

                $user = $model->where($map)->find();
                if (!$user) {
                    Log::write(var_export($map, true), 'map');
                    continue;
                }
                $addData['lottery_time'] = array('exp', 'lottery_time+1');
                $res = $model->where($map)->save($addData);
                if($res === false){
                    $update = false;
                    break;
                }

                $record['user_id'] = $user['id'];
                $record['score'] = ($score+$task_scope);
                $record['consume'] = $record['score'];
                $record['expire_time']=time()+$expire['value']*3600*24;

                $record['add_time'] = time();
                $record['type'] = 2;
                $scoreRes = M("PScoreRecord")->add($record);
                if(!$scoreRes){
                    $update = false;
                    break;
                }

            } 
            fclose($handle); //关闭指针 
            unlink($filename);
            
            if($update){
                $model->commit();
                $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'部分用户积分已变更，详情请查看积分记录！'));
            }else{
                $model->rollback();
                $this->ajaxReturn(array('errcode'=>10002, 'errmsg'=>'更新积分失败'));  
            }
        }else{
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'请上传文件'));
        }

    }

    //excel格式导入
    // public function import1()
    // {
    //     require_once(LIB_PATH.'Org/Util/PHPExcel/PHPExcel.class.php');
    //     if(!empty($_FILES)){
    //         $config = array(
    //             'exts'=>array('xlsx', 'xls'),
    //             'maxSixe' => 1024 * 1024 * 5,
    //             'rootPath' =>'./Uploads/',
    //             'savePath' =>'image/',
    //             'subName'  =>array('date', 'Ymd'),
    //             'driver' =>'Local'
    //             );
    //         $upload = new \Think\Upload($config);
    //         if(!$info = $upload->upload()){
    //             $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>$upload->getError()));
    //         }
    //         $filename = $upload->rootPath.$info['file']['savepath'].$info['file']['savename'];
    //         $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    //         if($extension == 'xlsx'){
    //             require_once(LIB_PATH.'Org/Util/PHPExcel/PHPExcel/Reader/Excel2007.php');
    //             $reader = new \PHPExcel_Reader_Excel2007();   
    //             $obj = $reader->load($filename, $encode = 'utf-8');
    //         }elseif ($extension == 'xls'){
    //             require_once(LIB_PATH.'Org/Util/PHPExcel/PHPExcel/Reader/Excel5.php');
    //             $reader = new \PHPExcel_Reader_Excel5();
    //             $obj = $reader->load($filename, $encode = 'utf-8');
    //         }
    //         $sheet = $obj->getSheet(0);
    //         $row = $sheet->getHighestRow();
    //         $col = $sheet->getHighestColumn();
    //         $add = 0;
    //         $dec = 0;
    //         $noChange = 0;
            
    //         $model = M("PUser");
    //         $model->startTrans();
    //         $update = true;
    //         for($i = 1; $i<= $row; $i++){
    //             $name = $obj->getActiveSheet()->getCell("A".$i)->getValue();
    //             $phone = $obj->getActiveSheet()->getCell("B".$i)->getValue();
    //             $account = $obj->getActiveSheet()->getCell("C".$i)->getValue();
    //             //$score = $obj->getActiveSheet()->getCell("D".$i)->getValue();
    //             $amount = $obj->getActiveSheet()->getCell("E".$i)->getValue();
    //             if($name instanceof \PHPExcel_RichText){
    //                 $name = $name->getPlainText();
    //             }
    //             if($phone instanceof \PHPExcel_RichText){
    //                 $phone = $phone->getPlainText();
    //             }
    //             if($account instanceof \PHPExcel_RichText){
    //                 $account = $account->getPlainText();
    //             }
    //             // if($score instanceof \PHPExcel_RichText){
    //             //     $score = $score->getPlainText();
    //             // }
    //             // $score = intval($score);
    //             // if($score < 0){
    //             //     $score = 0;
    //             // }
    //             if ($amount instanceof \PHPExcel_RichText) {
    //                 $amount = $amount->getPlainText();
    //             }
    //             if (empty(trim($name))) {
    //                 break;
    //             }
    //             $amount = trim($amount);
    //             if (empty($amount)) {//金额为空，不处理
    //                 continue;
    //             }
    //             $amount = str_replace(',', '', $amount);
    //             $amount = intval($amount);
    //             if ($amount <= 0) { //负增长，不处理
    //                 continue;
    //             }elseif ($amount < 10000){   //资金小于10000，不处理
    //                 continue;
    //             }elseif ($amount < 50000){  //5W以下加50积分 
    //                 $score = 58;
    //             }elseif ($amount < 100000){
    //                 $score = 108;
    //             }elseif ($amount < 500000){
    //                 $score = 158;
    //             }else{
    //                 $score = 208;
    //             }

    //             $start = strtotime($this->start);
    //             $end = strtotime($this->end);
    //             $now = time();
    //             //特定时期积分加倍
    //             if ($now >= $start and $now <= $end) {
    //                 $score = $score * 2;
    //             }

    //             $map['phone'] = trim($phone);
    //             $map['name'] = trim($name);
    //             $map['account'] = trim($account);
    //             if($map['name'] == '姓名' and $map['phone'] == '手机号码'){
    //                 continue;
    //             }
    //             $user = $model->where($map)->find();
    //             if (!$user) {
    //                 $noChange++;
    //                 continue;
    //             }
    //             $data['score'] = array('exp', 'score+'.$score);
    //             $data['lottery_time'] = array('exp', 'lottery_time+1');
    //             $res = $model->where($map)->save($data);
    //             if($res === false){
    //                 $update = false;
    //                 break;
    //             }

    //             $record['user_id'] = $user['id'];
    //             $record['score'] = $score;
    //             $record['add_time'] = time();
    //             $record['type'] = 2;
    //             $scoreRes = M("PScoreRecord")->add($record);
    //             if(!$scoreRes){
    //                 $update = false;
    //                 break;
    //             } 
    //         }
    //         unlink($filename);

    //         if($update){
    //             $model->commit();
    //             $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'部分用户积分已变更，详情请查看积分记录！'));
    //         }else{
    //             $model->rollback();
    //             $this->ajaxReturn(array('errcode'=>10002, 'errmsg'=>'更新积分失败'));  
    //         }
    //     }else{
    //         $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'请上传文件'));
    //     }

    // }
   

    public function upload()
    {
        if(!empty($_FILES)){
            $upload = new \Think\Upload(C('UPLOAD_CONFIG'));
            $info = $upload->upload($_FILES);
            $urls = array();
            if (!$info) {// 上传错误提示错误信息
                $data=array('err_code'=>403,'state'=>$upload->getError());
                echo json_encode($data);
                //$this->ajaxReturn($data,'JSON');
            } else {// 上传成功 获取上传文件信息
                foreach ($info as $file) {
                    //$url = $file['savepath'] . $file['savename'];
                   // var_dump($info);exit;
                    array_push($urls, $file);
                }
                $data=array('err_code'=>200,'err_msg'=>$urls,'state'=>'SUCCESS','url'=>$urls[0]['url']);
                Log::write(var_export($data, true), 'info');
                echo json_encode($data);
            //    $this->ajaxReturn($data);
            }
        }else{
            echo json_encode(array('state'=>'没有文件被上传'));
        }
    }

    public function loadConfig(){
        $list = M("PConfig")->select();
        $res =  array('data'=>$list);
        return $this->ajaxReturn(array_merge($this->return, $res));

    }

    public function editConfig(){
        $data['value'] = I('post.sign', '', 'trim');
        $taskWhereParam['key']='sign';
        M("PConfig")->where($taskWhereParam)->save($data);

        $data['value'] = I('post.task_expire', '', 'trim');
        $taskWhereParam['key']='task_expire';
        M("PConfig")->where($taskWhereParam)->save($data);

        $data['value'] = I('post.wheel_expire', '', 'trim');
        $taskWhereParam['key']='wheel_expire';
        M("PConfig")->where($taskWhereParam)->save($data);

        $data['value'] = I('post.sign_expire', '', 'trim');
        $taskWhereParam['key']='sign_expire';
        M("PConfig")->where($taskWhereParam)->save($data);

        $data['value'] = I('post.import_expire', '', 'trim');
        $taskWhereParam['key']='import_expire';
        M("PConfig")->where($taskWhereParam)->save($data);


        $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>''));

    }


    public function resetScore(){


        /*
        $where['type']=2;
        $where['is_deleted']=0;

        $where['add_time']=array('between',array(1507601880,1507602020));


        $array=M("PScoreRecord")->field('id,user_id,score')->where($where)->order('id desc')->select();
        unset($where);
        M("PUser")->startTrans();

        echo "ok";

        foreach ($array as $v) {
         echo "ok1";
            $where['id']=$v['user_id'];
            $user=M("PUser")->where($where)->find();
            $user['score']=$user['score']-$v['score'];
            if($user['score']<1){
                $user['score']=0;
            }
            M("PUser")->where($where)->save($user);
        }

        M("PUser")->commit();

        */
         echo "ok3";
    }

    public function resetUser(){
        echo 'ok1';
        /*
        $array=M("PUser")->where(array('is_deleted'=>0))->limit(60001, 20000)->select();
        M()->startTrans();

        foreach ($array as $v) {
            M("PScoreRecord")->add(array('user_id'=>$v['id'],'type'=>7,'score'=>$v['score'],'add_time'=>1514736000,'expire_time'=>1517414399,'consume'=>$v['score']));
        }

        M()->commit();
        */
        echo 'ok2';
    }

}